package com.newtouch.avmarketing.mgr.modules.avmarkrting.service.impl;

import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.DoubleAuditing;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.VideoInformation;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.repo.DoubleAuditingRepo;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.repo.VideoInformationRepo;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.DoubleAuditingService;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.DoubleConfigurationService;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.FileUploadService;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.VideoInformationService;
import com.newtouch.avmarketing.mongo.po.PolicyPo;
import com.newtouch.avmarketing.mongo.service.InsurancePolicyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private DoubleConfigurationService doubleConfigurationService;
    @Autowired
    private InsurancePolicyService insurancePolicyService;
    @Autowired
    private VideoInformationService videoInformationService;
    @Autowired
    private DoubleAuditingService doubleAuditingService;
    @Autowired
    private DoubleAuditingRepo doubleAuditingRepo;
    @Autowired
    private VideoInformationRepo videoInformationRepo;
    @Value("${file.save_path}")
    private String save_path;

    public static void main(String[] args) throws ParseException {
        String startTime = "11:29:17";
        String endTime = "11:30:17";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date parse1 = sdf.parse(startTime);
        Date parse2 = sdf.parse(endTime);
        System.out.println("parse1"+parse1);
        System.out.println("parse2"+parse2);

        int timeSize = (int) (parse2.getTime() - parse1.getTime()) / 1000;

        System.out.println("timeSize:"+ timeSize);
    }

    @Override
    public Map<String, Object> uploadFile(MultipartFile file, HttpServletRequest request, String policyCode) throws Exception {
        Map<String, Object> map = new HashMap<>();
        PolicyPo policyPo = insurancePolicyService.findPolicy(policyCode);

        String unitName = "上海分公司";
        String branchName = "上海中支公司";
        String fourBranchName = "高科新路分公司";
        String productName = "产品测试";
        String isValid = "1";//1:生效 0:未生效
        String policyName = "张三";
        String marketEmp = "0202002";
        String marketName = "小张";
        String phoneNumber = "13670893042";
        String insureTime = "2021-06-15";
        String checkStatus = "0";//1:已审核 0:未审核 2:审核不通过

        String path = null;// 文件路径
        double fileSize = file.getSize();
        // 首先先将.getSize()获取的Long转为String 然后将String转为Float并除以1024 （因为1KB=1024B）
        Float size = Float.parseFloat(String.valueOf(file.getSize())) / 1024;
        BigDecimal b = new BigDecimal(size / 1024);
        // 2表示2位 ROUND_HALF_UP表明四舍五入，
        size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        String sizes = size.toString(size) + "M";
        // 此时size就是保留两位小数的浮点数
        System.out.println("文件的大小是" + fileSize);

        if (file != null) {// 判断上传的文件是否为空
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            System.out.println("上传的文件原名称:" + fileName);
            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
                if ("MP4".equals(type.toUpperCase())
                        || "GIF".equals(type.toUpperCase())
                        || "PNG".equals(type.toUpperCase())
                        || "JPG".equals(type.toUpperCase())
                        || "AVI".equals(type.toUpperCase())
                ) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    // 设置存放图片文件的路径
                    path = save_path + fileName;
                    System.out.println("存放图片文件的路径:" + path);
                    // 转存文件到指定的路径
                    file.transferTo(new File(path));

                    MultimediaObject instance = new MultimediaObject(new File(path));
                    MultimediaInfo result = instance.getInfo();
                    long ls = result.getDuration() / 1000; //秒
                    long ms = ls % 60 % 60; //取余后的秒数
                    String mss = null;
                    String mins = null;
                    if (ms < 10) {
                        mss = "0" + ms;
                    } else {
                        mss = String.valueOf(ms);
                    }
                    String s = String.valueOf(ms);
                    System.out.println("StringMS: " + s);
                    long min = ls / 60;//分钟;
                    if (min < 10) {
                        mins = "0" + min;
                    } else {
                        mins = String.valueOf(min);
                    }
                    String videoTime = mins + ":" + mss;
                    System.out.println("videoTime:" + videoTime);
                    System.out.println("文件成功上传到指定目录下");

                    DoubleAuditing byPolicyCode = doubleAuditingRepo.findByPolicyCode(policyCode);

                    if (byPolicyCode == null) {
                        DoubleAuditing doubleAuditing = new DoubleAuditing();
                        doubleAuditing.setUnitCode("12");
                        doubleAuditing.setUnitName(unitName);
                        doubleAuditing.setBranchCode("12");
                        doubleAuditing.setBranchName(branchName);
                        doubleAuditing.setFourBranchCode("12");
                        doubleAuditing.setFourBranchName(fourBranchName);
                        doubleAuditing.setProductName(productName);
                        doubleAuditing.setCheckEmp("admin");
                        doubleAuditing.setCheckName("管理员");
                        doubleAuditing.setIsValid(isValid);
                        doubleAuditing.setPolicyCode(policyCode);
                        doubleAuditing.setPolicyName(policyName);
                        doubleAuditing.setMarketEmp(marketEmp);
                        doubleAuditing.setMarketName(marketName);
                        doubleAuditing.setPhoneNumber(phoneNumber);
                        doubleAuditing.setInsureTime(LocalDateTime.now().toString());
                        doubleAuditing.setCheckStatus(checkStatus);
                        doubleAuditing.setVideoPath(path);
                        doubleAuditing.setVideoSize(sizes);
                        doubleAuditing.setPolicyAge("20");
                        doubleAuditing.setVideoTime(videoTime);

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        doubleAuditing.setUploadTime(format.format(new Date()));

                        doubleAuditingRepo.save(doubleAuditing);
                        System.out.println("插入成功");
                        map.put("doubleAuditing", doubleAuditing);
                        map.put("message", "新增一条双录记录");
                    } else {
                        byPolicyCode.setVideoPath(path);
                        byPolicyCode.setVideoSize(sizes);
                        byPolicyCode.setVideoTime(videoTime);
                        doubleAuditingRepo.saveAndFlush(byPolicyCode);
                        System.out.println("更新成功");
                        map.put("byPolicyCode", byPolicyCode);
                        map.put("message", "更新双录视频成功");
                    }
                    return map;
                }
            } else {
                System.out.println("不是我们想要的文件类型,请按要求重新上传");
                return map;
            }
        } else {
            System.out.println("文件类型为空");
            return map;
        }
        return map;
    }
    @Override
    public Map<String, Object> updateVideoInfo(String policyCode,String endTime, List<VideoInformation> list) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<VideoInformation> videoInformationList = videoInformationService.findByPolicyCode(policyCode);
        List s=new ArrayList();

        if (videoInformationList.size() == 0) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println("list(i):" + list.get(i).toString());

                VideoInformation videoInformation1 = list.get(i);
                VideoInformation videoInformation = new VideoInformation();

                videoInformation.setPolicyCode(policyCode);
                videoInformation.setStepId(videoInformation1.getStepId());
                videoInformation.setStepName(doubleConfigurationService.findByIds(videoInformation1.getStepId()).getStepName());
                videoInformation.setNodeStart(videoInformation1.getNodeStart());
                videoInformation.setNodeEnd(videoInformation1.getNodeEnd());
                videoInformation.setTag(videoInformation1.getTag());

                //更新双录记录表 录像完成时间
                doubleAuditingService.updateDoubleAuditingEndTime(policyCode,endTime);
                videoInformationRepo.save(videoInformation);

                s.add(videoInformation);
                map.put("videoInformation", s);
                map.put("message", "生成节点信息成功");
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                VideoInformation videoInformation1 = list.get(i);
                for (int j = 0; j < videoInformationList.size(); j++) {
                    VideoInformation videoInformation2 = videoInformationList.get(j);
                    if (videoInformation2.getStepId().equals(videoInformation1.getStepId())) {
                        videoInformation2.setStepName(doubleConfigurationService.findByIds(videoInformation1.getStepId()).getStepName());
                        videoInformation2.setPolicyCode(policyCode);
                        videoInformation2.setNodeStart(videoInformation1.getNodeStart());
                        videoInformation2.setNodeEnd(videoInformation1.getNodeEnd());
                        videoInformation2.setTag(videoInformation1.getTag());

                        //更新双录记录表 录像完成时间
                        doubleAuditingService.updateDoubleAuditingEndTime(policyCode,endTime);
                        videoInformationRepo.saveAndFlush(videoInformation2);
                        s.add(videoInformation2);
                        map.put("videoInformationList", s);
                        map.put("message", "更新节点信息成功");
                    }
                }
            }
        }
        return map;
    }
    @Override
    public Map<String, Object> updateVideoInfoId(String policyCode, List<Long> idList) {
        Map<String, Object> map = new HashMap<>();
        List<VideoInformation> videoInformationList = videoInformationService.findByPolicyCode(policyCode);

        if (videoInformationList.size() == 0) {
            for (int i = 0; i < idList.size(); i++) {
                Long ids = idList.get(i);
                VideoInformation videoInformation = new VideoInformation();
                videoInformation.setStepId(ids.longValue());
                videoInformation.setPolicyCode(policyCode);
                videoInformationRepo.save(videoInformation);

                map.put("videoInformation", videoInformation);
                map.put("message", "生成节点信息成功");
            }
        }
        return map;
    }
}